package com.bng8.superstar_cms.controller;

import com.bng8.superstar_cms.domain.common.ResponseResult;
import com.bng8.superstar_cms.domain.dto.SupChallengerDTO;
import com.bng8.superstar_cms.exception.ErrorCodeEnum;
import com.bng8.superstar_cms.service.SupChallengerService;
import com.bng8.superstar_cms.util.InsertValidationGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * ClassName: ChallengerController
 * Package: com.bng8.superstar_cms.controller
 * Date: 2023/8/17 14:01
 * Author: 安知（13921877634）
 */
@Slf4j
@Validated
@RestControllerAdvice
@RequestMapping("/api/challenger")
public class ChallengerController {
    @Autowired
    private SupChallengerService challengerService;

    /**
     * 新增挑战者
     *
     * @param request
     * @param challengerDTO
     * @return
     */
    @PostMapping
    @CacheEvict(cacheNames = "challenger-cache", allEntries = true)
    public ResponseResult save(HttpServletRequest request,
                               @Validated(InsertValidationGroup.class)
                               @RequestBody SupChallengerDTO challengerDTO) {

        int save = challengerService.save(request, challengerDTO);
        if (save != 1) return ResponseResult.failure(ErrorCodeEnum.NICK_REPEAT_FAILURE);
        return ResponseResult.success("新增成功");
    }

    /**
     * 逻辑删除挑战者
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @CacheEvict(cacheNames = "challenger-cache", key = "#id")
    public ResponseResult delete(HttpServletRequest request, @NotNull @PathVariable("id") Long id) {
        int deleter = challengerService.deleter(request, id);
        if (deleter == 1) return ResponseResult.success("删除成功");
        return ResponseResult.failure(ErrorCodeEnum.DELETE_FAILURE);
    }

    @GetMapping
    @Cacheable(cacheNames = "challenger-cache")
    public ResponseResult getChallengerByUserId(/*@NotNull @PathVariable("id") Long id*/) {
        List<SupChallengerDTO> challengerDOS = challengerService.queryChallengerByUserId();
        return ResponseResult.success(challengerDOS);
    }
}
